package file

import (
	"fmt"
	"os"
	"path"
	"reflect"
	"runtime"
	"time"
)

const (
	glargeSysLog = "log/sys.log"
	appandStr1   = "====="
	appandStr2   = "OUTPUT"
	infopath     = "log/info.log"
)

// WriteFile internal write
func WriteFile(logLevel, filePath, format string, args interface{}) {
	if filePath != infopath {
		fmt.Printf("%s, %s\n", string(infopath), reflect.ValueOf(filePath))
	}
	fileobj, err := os.OpenFile(string(filePath), os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0644)
	defer fileobj.Close()
	if err != nil {
		Syslog(err)
	}
	// TODO 拼接字符串
	timeStr := gettimestr()
	pc, file, line, _ := runtime.Caller(2) // runtime caller 学习
	funcname := runtime.FuncForPC(pc).Name()
	filename := path.Base(file)
	input1 := fmt.Sprintf(format, args)
	input2 := fmt.Sprintf("【%s】%s %s %s %s file %s func:%s line:%d %s \n", timeStr, appandStr1, logLevel, appandStr2, appandStr1, filename, funcname, line, input1)
	fileobj.WriteString(input2)
}

// ReadFile internal write
func ReadFile(filePath string) {
}

// Syslog 系统writer
func Syslog(errormsg error) {
	fileobj, _ := os.OpenFile(glargeSysLog, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0644)
	defer fileobj.Close()
	fileobj.WriteString(errormsg.Error() + "\n")
}

func gettimestr() string {
	now := time.Now()
	return now.Format("2020-2-21 13:04:05")
}
